package com.dstz.org.core.script;

import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.dstz.base.api.exception.BusinessMessage;
import com.dstz.base.api.query.QueryFilter;
import com.dstz.base.core.util.StringUtil;
import com.dstz.base.db.model.query.DefaultQueryFilter;
import com.dstz.org.api.constant.GroupTypeConstant;
import com.dstz.org.api.model.IGroup;
import com.dstz.org.api.model.IUser;
import com.dstz.org.api.service.GroupService;
import com.dstz.org.api.service.UserService;
import com.dstz.org.core.manager.GroupManager;
import com.dstz.org.core.manager.RoleManager;
import com.dstz.org.core.model.Role;
import com.dstz.sys.api.groovy.IScript;
import com.dstz.sys.api.model.DefaultIdentity;
import com.dstz.sys.api.model.SysIdentity;
import com.dstz.sys.util.ContextUtil;

/**
 * <pre>
 * 描述：常用org的脚本
 * 作者:aschs
 * 邮箱:aschs@qq.com
 * 日期:2019年5月26日
 * 版权:summer
 * </pre>
 */
@Component
public class OrgScript implements IScript {
	@Resource
	GroupService groupService;
	@Resource
	UserService userService;
	@Resource
	GroupManager groupMananger;
	@Resource
	RoleManager roleManager;

	/**
	 * 检查某用户是否拥有某角色
	 * 
	 * @param userId
	 *            用户ID
	 * @param roleCode
	 *            角色CODE
	 * @return
	 */
	public boolean checkUserHasRole(String userId, String roleCode) {
		if(StringUtil.isEmpty(userId)) {
			userId = ContextUtil.getCurrentUserId();
		}
		
		List<? extends IGroup> roleList = groupService.getGroupsByGroupTypeUserId(GroupTypeConstant.ROLE.key(), userId);
		for (IGroup group : roleList) {
			if (group.getGroupCode().equals(roleCode)) {
				return true;
			}
		}

		return false;
	}
	
	/**
	 * 获取角色的Level
	 * @param userId
	 * @return
	 */
	public Integer getUserRoleLevel(String userId) {
		if(StringUtil.isEmpty(userId)) {
			userId = ContextUtil.getCurrentUserId();
		}
		Integer level =  -1;
		List<? extends IGroup> roleList = groupService.getGroupsByGroupTypeUserId(GroupTypeConstant.ROLE.key(), userId);
		for (IGroup group : roleList) {
			if (group.getGroupLevel() != null && group.getGroupLevel()> level) {
				level = group.getGroupLevel();
			}
		}

		return level;
	}
	
	public Integer getOrgLevel(String orgId) {
		if(StringUtil.isEmpty(orgId)) {
			orgId = ContextUtil.getCurrentGroupId();
		}
		
		IGroup org = groupService.getById(GroupTypeConstant.ORG.key(), orgId);
		if(org== null)return -1;
		
		return org.getGroupLevel();
	}

	/**
	 * <pre>
	 * 获取某个组织下的某些角色的人员列表
	 * </pre>
	 * 
	 * @param groupIds
	 *            组织id，多个以“,”分隔；为空，则取当前用户所在主组织
	 * @param roleCodes
	 *            角色编码，多个以“,”分隔
	 * @return
	 */
	public Set<SysIdentity> getSisByGroupAndRole(String groupIds, String roleCodes) {
		Set<SysIdentity> identities = new HashSet<>();
		if (StringUtil.isEmpty(groupIds)) {
			if (ContextUtil.getCurrentGroup() == null) {
				throw new BusinessMessage("请为当前人员分配组织");
			}
			groupIds = ContextUtil.getCurrentGroup().getGroupId();
		}
		for (String gi : groupIds.split(",")) {
			List<? extends IUser> users = userService.getUserListByGroup(GroupTypeConstant.ORG.key(), gi);
			users.forEach(user -> {
				List<? extends IGroup> roles = groupService.getGroupsByGroupTypeUserId(GroupTypeConstant.ROLE.key(), user.getUserId());
				roles.forEach(role -> {
					if (roleCodes.contains(role.getGroupCode())) {
						SysIdentity identity = new DefaultIdentity(user.getUserId(), user.getFullname(), SysIdentity.TYPE_USER);
						identities.add(identity);
					}
				});
			});
		}

		return identities;
	}
	
	
	
	/**
	 * 获取指定组织上级的人员
	 * @param groupId
	 * @param level
	 * @return
	 */
	public IGroup getSpecificSuperOrg(String groupId,int level){
		if (StringUtil.isEmpty(groupId)) {
			groupId = ContextUtil.getCurrentGroupId();
		}
		
		IGroup group = groupService.getById(GroupTypeConstant.ORG.key(), groupId);
		if(group!=null &&  group.getGroupLevel()==level) {
			return group;
		}
		
		return getParentByType(group, level);
	}
	
	public Set<SysIdentity> getSpecificSuperOrgIdentity(String groupId,int level){
		IGroup group = this.getSpecificSuperOrg(groupId, level);
		if(group==null) return Collections.emptySet();
		
		Set<SysIdentity> identities = new HashSet<>();
		SysIdentity identity = new DefaultIdentity(group.getGroupId(), group.getGroupName(), SysIdentity.TYPE_ORG);
		identities.add(identity);
		return identities;
	}
	
	public Set<SysIdentity> getSpecificSuperPostIdentity(String groupId,int level,String roleCodes){
		IGroup group = this.getSpecificSuperOrg(groupId, level);
		if(group==null) return Collections.emptySet();
		
		List<? extends IUser> users = userService.getUserListByGroup(GroupTypeConstant.ORG.key(), group.getGroupId());
		Set<SysIdentity> identities = new HashSet<>();
		users.forEach(user -> {
				List<? extends IGroup> roles = groupService.getGroupsByGroupTypeUserId(GroupTypeConstant.ROLE.key(), user.getUserId());
				roles.forEach(role -> {
					if (roleCodes.contains(role.getGroupCode())) {
						SysIdentity identity = new DefaultIdentity(user.getUserId(), user.getFullname(), SysIdentity.TYPE_USER);
						identities.add(identity);
					}
				});
		});
		return identities;
	}
	
	
	
	private IGroup getParentByType(IGroup group,int type) {
		if(group== null) return null;
		
		IGroup parentGroup = groupService.getById(GroupTypeConstant.ORG.key(), group.getParentId());
		if(parentGroup != null && parentGroup.getGroupLevel()==type) {
			return parentGroup;
		}
		return getParentByType(parentGroup, type);
	}
	
	/**
	 * <pre>
	 * 根据角色条件获取角色候选组
	 * eg:
	 * 获取级别大于等于50 小于等于60：
	 * orgScript.getRoleSis("level_ >= 50 and level_ <= 60")
	 * </pre>	
	 * @param where
	 * @return
	 */
	public Set<SysIdentity> getRoleSis(String where) {
		QueryFilter filter = new DefaultQueryFilter();
    	filter.addParamsFilter("defaultWhere", where);
		List<Role> roles = roleManager.query(filter);
		Set<SysIdentity> roleSis = new HashSet<>();
		roles.forEach(role -> {
			SysIdentity identity = new DefaultIdentity(role.getId(), role.getName(), SysIdentity.TYPE_ROLE);
			roleSis.add(identity);
		});
		
		return roleSis;
	}
}
